$(document).ready(function(){
  
  $('#refreshPlaylist').click(function() { 
      updatePlaylist();
      return false;
  });
  
  function updatePlaylist() {
    //get the updated playlist
    $.getJSON('playlistmanager.php?action=getJSONplaylist',
          function(data){
              //put the JSON data into the playlist array.
              myPlayList=data;
              //clear the playlist
              $("#playlist_list ul").html("");
              //then redisplay it
              displayPlayList();
              //make sure the playing item is highlighted properly
              //loop through the myPlayList array and find the id based on the name
              var z;
              for(z in myPlayList){
                  if(myPlayList[z].name == playItemName){
                      $("#playlist_item_"+z).addClass("playlist_current");
                  }
              }
          });
  }
  
  //MENUS
  // BUTTONS
  $('.fg-button').hover(
    function(){ $(this).removeClass('ui-state-default').addClass('ui-state-focus'); },
    function(){ $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }
  );
      
  $('#flat').menu({ 
    content: $('#flat').next().html(), // grab content from this page
    showSpeed: 400 
  });
  var global_lp = 0;
  var playItem = 0;

  var myPlayList = [ <? getJSONplaylist(); ?> ];

  $("#jquery_jplayer").jPlayer({
    ready: function ()
    {
      displayPlayList();
      playListInit(true); // Parameter is a boolean for autoplay.
      //demoInstanceInfo($(this), $("#jplayer_info"));

      //$(this).setFile('http://www.miaowmusic.com/mp3/Miaow-05-The-separation.mp3').play();
      showPauseBtn();
      demoInstanceInfo($(this), $("#jplayer_info"));
    }
  })
  .onProgressChange( function(lp,ppr,ppa,pt,tt) {
    var lpInt = parseInt(lp);
    var ppaInt = parseInt(ppa);
    global_lp = lpInt;

    $('#loaderBar').progressbar('option', 'value', lpInt);
    $('#sliderPlayback').slider('option', 'value', ppaInt);
  })
  .onSoundComplete( function() {
    //$(this).play();
    playListNext();
  });

  $("#pause").hide();

  function showPauseBtn()
  {
    $("#play").fadeOut(function(){
      $("#pause").fadeIn();
    });
  }

  function showPlayBtn()
  {
    $("#pause").fadeOut(function(){
      $("#play").fadeIn();
    });
  }

  function playTrack(t,n)
  {
    $("#jquery_jplayer").setFile(t).play();

    showPauseBtn();

    return false;
  }

  $("#play").click(function() {
    $("#jquery_jplayer").play();
    showPauseBtn();
    return false;
  });

  $("#pause").click(function() {
    $("#jquery_jplayer").pause();
    showPlayBtn();
    return false;
  });

  $("#stop").click(function() {
    $("#jquery_jplayer").stop();
    showPlayBtn();
    return false;
  });


  $("#volume-min").click( function() {
    $('#jquery_jplayer').volume(0);
    $('#sliderVolume').slider('option', 'value', 0);
    return false;
  });

  $("#volume-max").click( function() {
    $('#jquery_jplayer').volume(100);
    $('#sliderVolume').slider('option', 'value', 100);
    return false;
  });

  $("#player_progress_ctrl_bar a").live( "click", function() {
    $("#jquery_jplayer").playHead(this.id.substring(3)*(100.0/global_lp));
    return false;
  });

  // Slider
  $('#sliderPlayback').slider({
    max: 100,
    range: 'min',
    animate: true,

    slide: function(event, ui)
    {
      $("#jquery_jplayer").playHead(ui.value*(100.0/global_lp));
    }
  });

  $('#sliderVolume').slider({
    value : 50,
    max: 100,
    range: 'min',
    animate: true,

    slide: function(event, ui)
    {
      $("#jquery_jplayer").volume(ui.value);
    }
  });

  $('#loaderBar').progressbar();


  //hover states on the static widgets
  $('#dialog_link, ul#icons li').hover(
    function() { $(this).addClass('ui-state-hover'); },
    function() { $(this).removeClass('ui-state-hover'); }
  );
  
  $("#ctrl_prev").click( function() {
    playListPrev();
    return false;
  });

  $("#ctrl_next").click( function() {
    playListNext();
    return false;
  });

  function displayPlayList() {
    for (i=0; i < myPlayList.length; i++) {
      $("#playlist_list ul").append("<li id='playlist_item_"+i+"'>"+ myPlayList[i].name +"</li><img src='images/cross.png' id='playlist_item_remove_"+i+"' class='removePlaylistItem'/>");
      $("#playlist_item_"+i).data( "index", i ).hover(
        function() {
          if (playItem != $(this).data("index")) {
            $(this).addClass("playlist_hover");
          }
        },
        function() {
          $(this).removeClass("playlist_hover");
        }
      ).click( function() {
        var index = $(this).data("index");
        if (playItem != index) {
          playListChange( index );
          showPauseBtn();
        }
      });
      $("#playlist_item_remove_"+i).data( "index", i ).click( function() {
        var index = $(this).data("index");
        //send the request to remove the playlist item
        //alert("Attempting to remove " +myPlayList[index].name+" via index: "+index);
        $.getJSON('playlistmanager.php?action=ajaxDeletePlaylistItem&playlistItem='+index,
          function(data, textStatus){
            if(textStatus == "success" && data[0].deleted == true){
                //alert("Request successful. About to hide "+myPlayList[index].name+" via index: "+index+" phpItemID: "+data[0].phpitemID+" phpName: "+data[0].phpitemName);
                //then hide the related items
                $("#playlist_item_"+index).hide('explode',500);
                $("#playlist_item_remove_"+index).hide('explode');
                //if the playing item is removed the playItem variable needs to be cleared
                if(playItem == index){
                    playItem=-1;
                }
                //update the playlist
                updatePlaylist();
            }
        });
      });
    }
  }

  function playListInit(autoplay) {
    if(autoplay) {
      playListChange( playItem );
    } else {
      playListConfig( playItem );
    }
  }

  function playListConfig( index ) {
    $("#playlist_item_"+playItem).removeClass("playlist_current");
    $("#playlist_item_"+index).addClass("playlist_current");
    playItem = index;
    playItemName = myPlayList[index].name; //added this to track the now playing name JLHACK
    $("#jquery_jplayer").setFile(myPlayList[playItem].mp3, myPlayList[playItem].ogg);
  }

  function playListChange( index ) {
    playListConfig( index );
    $("#jquery_jplayer").play();
  }

  function playListNext() {
    var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
    playListChange( index );
  }

  function playListPrev() {
    var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
    playListChange( index );
  }


});